package com.tlsy.commerce.service.impl;

import com.tlsy.commerce.dao.RoleDao;
import com.tlsy.commerce.dao.UserDao;
import com.tlsy.commerce.model.Role;
import com.tlsy.commerce.model.User;
import com.tlsy.commerce.model_enum.RoleTypeEnum;
import com.tlsy.commerce.model_enum.StatusEnum;
import com.tlsy.commerce.model_enum.UserTypeEnum;
import com.tlsy.commerce.service.SystemService;
import com.tlsy.commerce.utils.AppUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Tlsy
 * @version commerce 0.0.1
 * @date 2017/4/24  15:27
 */
@Service
public class SystemServiceImpl implements SystemService{

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private UserDao userDao;

    @Override
    @Transactional
    public void addAndUpdateRole(Role role) {
        roleDao.save(role);
    }

    @Override
    public void deleteRole(Role role) {

        roleDao.delete(role);
    }


    @Override
    public Role findRoleById(String roleId) {
        return roleDao.findOne(roleId);
    }



    public User findUserByPhone(String phone) {
        return userDao.findUserByPhone(phone);
    }

    @Override
    public void addAndUpdateUser(User user) {
        userDao.save(user);
    }

    @Override
    public void deleteUser(User user) {
        userDao.delete(user);
    }


    @Override
    public User findUserById(String userId) {
        return userDao.findOne(userId);
    }

    public List<Role> findRolesByRoleType(RoleTypeEnum typeEnum){
        return roleDao.findRolesByTypeAndAndStatus(typeEnum,StatusEnum.ENABLED);
    }

    @Override
    @Transactional
    public void register(User user) {
        user.setStatus(StatusEnum.ENABLED);
        user.setType(UserTypeEnum.BUYER);
        user.setPassword(AppUtil.entryptPassword(user.getPassword()));
        user.setRoles(findRolesByRoleType(RoleTypeEnum.BUYER));
        addAndUpdateUser(user);
    }
}
